package com.baomidou.springwind.controller;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sun.image.codec.jpeg.JPEGCodec;    
import com.sun.image.codec.jpeg.JPEGEncodeParam;    
import com.sun.image.codec.jpeg.JPEGImageEncoder; 

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.framework.common.util.DateUtil;
import com.baomidou.framework.controller.SuperController;
import com.baomidou.framework.upload.UploadFile;
import com.baomidou.framework.upload.UploadMsg;
import com.baomidou.framework.upload.UploadMultipartRequest;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springwind.common.HoorayosHelper;
import com.baomidou.springwind.entity.Member;
import com.baomidou.springwind.entity.Pwallpaper;
import com.baomidou.springwind.entity.Wallpaper;
import com.baomidou.springwind.service.IMemberService;
import com.baomidou.springwind.service.IPwallpaperService;
import com.sun.tools.internal.ws.wsdl.framework.Entity;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Koumiba
 * @since 2017-03-24
 */
@Controller
@RequestMapping("/sysapp/wallpaper")
public class WallpaperController extends SuperController {
	/* 限制最大上传 3M */
	private final static int MAX_POST_SIZE = 3 * 1024 * 1024;
	
	@Autowired
	private IMemberService memberService;
	@Autowired
	private IPwallpaperService pwallpaperService;
	/**
	 * 主页
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/index")
	public String index(Model model) {
		
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}
		EntityWrapper ew = new EntityWrapper<Member>();
		ew.and("tbid="+HoorayosHelper.getMemberId(request));
		Member member = new Member().selectOne(ew);
		model.addAttribute("wallpapertype", member.getWallpapertype());
		
		/*
		 * 获取所有壁纸并显示到view
		 */
		List<Wallpaper> wallpaperList = new Wallpaper().selectAll();
		String display = "";
		for(int i=0; i<wallpaperList.size(); i++){
			
			if(i % 3 ==2){
				display += "<li class='three' wpid='"+wallpaperList.get(i).getTbid()+"'>";
			}else{
				display += "<li wpid='"+wallpaperList.get(i).getTbid()+"'>";
			}
			display += "<img src='"+wallpaperList.get(i).getUrl()+"'>";
			display += "<div>"+wallpaperList.get(i).getTitle()+"</div>";
			display += "</li>";
		}
		model.addAttribute("display", display);
		return "/sysapp/wallpaper/index";
	}
	
	/**
	 * 自定义壁纸
	 * @param model
	 * @return String
	 * koumiba
	 * 2017年4月5日
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/custom")
	public String custom(Model model) {
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}	
		int mid = HoorayosHelper.getMemberId(request);
		Member member = memberService.selectById(mid);
		model.addAttribute("wallpaper", member);
		
		model.addAttribute("pwallpaper", pwallpaperService.selectById(mid));
	
		
		return "/sysapp/wallpaper/custom";
	}

	/**
	 * ajax 入口
	 * @param model
	 * @throws Exception 
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action=Action.Skip)
	@RequestMapping(value="/ajax", method = RequestMethod.POST)
	public String ajax(String ac) throws Exception{
		int mid = HoorayosHelper.getMemberId(request);
				
		if (ac.equals("del")){
			int id = Integer.parseInt(request.getParameter("id"));
			EntityWrapper ew = new EntityWrapper<Member>();
			ew.and("wallpaper_id="+id+" AND wallpaperstate=2");
			if(new Member().selectCount(ew) < 1){
				ew = new EntityWrapper<Pwallpaper>();
				ew.and("tbid="+id+" AND member_id="+mid);
				pwallpaperService.delete(ew);
			}else{
				return "ERROR";
			}			
		}else if(ac.equals("uploadImg")){
			long lastPwallpaperTbid = 1; //最后一条壁纸表的tbid
			//先验证图片是否超过6张，否则不允许上传
			EntityWrapper ew = new EntityWrapper<Pwallpaper>();
			ew.where("member_id="+mid);
			Map<String,String> json = new HashMap<String,String>();
			if(new Pwallpaper().selectCount(ew) < 6){
				UploadMsg msg = new UploadMsg();
				try {
					UploadMultipartRequest umr = new UploadMultipartRequest(request, getSaveDir(), MAX_POST_SIZE);
//					umr.setFileHeaderExts("ffd8ff.jpg");
					umr.upload();
					Enumeration<?> files = umr.getFileNames();
					while ( files.hasMoreElements() ) {
						String name = (String) files.nextElement();
						UploadFile cf = umr.getUploadFile(name);
						if ( cf != null ) {
							/**
							 * 上传成功
							 */
							if ( cf.isSuccess() ) {
								String newFilePath = cf.getFileUrl().replace(cf.getFilename(), "s_"+cf.getFilename());
								zipWidthHeightImageFile(new File(cf.getFileUrl()), new File(newFilePath), 150, 105); //压缩图片

					            //上传完毕后，添加数据库记录
								Image srcFile = ImageIO.read(new File(cf.getFileUrl()));    
						        int w = srcFile.getWidth(null);    
						        int h = srcFile.getHeight(null);    

						        // 先获取最后的一条数据tbid
						        ew = new EntityWrapper<Pwallpaper>();
						        ew.orderBy("tbid", false);
						        Pwallpaper pw = new Pwallpaper().selectOne(ew);
						        if(pw !=null)
						        	lastPwallpaperTbid = pw.getTbid();
						        
						        String url = getSurlPath() + cf.getFilename();
								String surl = getSurlPath() + "s_"+cf.getFilename();
								
								Pwallpaper pwallpaper = new Pwallpaper();
								pwallpaper.setUrl(url);
								pwallpaper.setWidth(w);
								pwallpaper.setHeight(h);
								pwallpaper.setMemberId((long)HoorayosHelper.getMemberId(request));
								pwallpaper.setTbid(lastPwallpaperTbid+1);
								
								pwallpaperService.insert(pwallpaper);
								/*
								 * 组装json数据以放回到view								
								 */
								json = new HashMap<String,String>();
								json.put("tbid", lastPwallpaperTbid+"");
								json.put("surl", surl);
								json.put("url", url);
								json.put("fileType", cf.getType());
								json.put("original", cf.getOriginal());
								json.put("state", cf.getUploadCode()+"");
							}
							
						}
					}
				} catch ( IOException e ) {
					logger.error("uploadFile error. ", e);
				}		
				
				return JSONUtils.toJSONString(json);
			}else{
				return "{'state':'您已经上传满6张壁纸，可以删除之后再进行上传'}";
			}		
						
		}
		
		return "";
	}
	
	
	/**
	 * <p>
	 * 上传文件存放目录 //uploads/member/'.session('member_id').'/wallpaper/{yyyy}{mm}{dd}
	 * </p>
	 */
	private String getSaveDir() {
		StringBuffer filePath = new StringBuffer(session.getServletContext().getRealPath("/"));
		filePath.append(File.separator).append("WEB-INF").append(File.separator).append("static")
		.append(File.separator).append("uploads").append(File.separator).append("member").append(File.separator);
		
		filePath.append(HoorayosHelper.getMemberId(request)).append(File.separator).append("wallpaper").append(File.separator);
		filePath.append(DateUtil.format(new Date(), "yyyyMMdd"));
		File file = new File(filePath.toString());
		if ( !file.exists() ) {
			file.mkdirs();
		}
		
		return file.getPath();
	}
	private String getSurlPath(){
		return "/static/uploads/member/"+HoorayosHelper.getMemberId(request)+"/wallpaper/"+DateUtil.format(new Date(), "yyyyMMdd")+"/";
	}
	 private String zipWidthHeightImageFile(File oldFile,File newFile, int width, int height) {    
	        if (oldFile == null) {    
	            return null;    
	        }    
	        String newImage = null;    
	        try {    
	            /** 对服务器上的临时文件进行处理 */    
	            Image srcFile = ImageIO.read(oldFile);    
//	            int w = srcFile.getWidth(null);    
//	            int h = srcFile.getHeight(null);    
	    
	            /** 宽,高设定 */    
	            BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);    
	            tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);    
	            //String filePrex = oldFile.substring(0, oldFile.indexOf('.'));    
	            /** 压缩后的文件名 */    
	            //newImage = filePrex + smallIcon+ oldFile.substring(filePrex.length());    
	    
	            /** 压缩之后临时存放位置 */    
	            FileOutputStream out = new FileOutputStream(newFile);    
	    
	            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);    
	            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);    
	            /** 压缩质量 */    
//	            jep.setQuality(quality, true);    
	            encoder.encode(tag, jep);    
	            out.close();
	          				
	        } catch (FileNotFoundException e) {    
	            e.printStackTrace();    
	        } catch (IOException e) {    
	            e.printStackTrace();    
	        }    
	        return newImage;    
	    }    
}
